package com.mid;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created by Lxk on 2019/5/16.
 */
public class Solution102 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode levelEnd = root;
        TreeNode lastNode = root;
        queue.offer(root);
        List<Integer> level = new ArrayList<>();
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur.left != null) {
                queue.offer(cur.left);
                lastNode = cur.left;
            }
            if (cur.right != null) {
                queue.offer(cur.right);
                lastNode = cur.right;
            }
            level.add(cur.val);
            if (cur == levelEnd) {
                levelEnd = lastNode;
                res.add(level);
                level = new ArrayList<>();
            }
        }
        return res;
    }

}
